﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    DicManagerViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/15 13:33:35

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.ViewModels.ViewModel.SystemManager;

/// <summary>
/// 字典管理ViewModel
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.DicManagerViewModel)]
public partial class DicManagerViewModel : BillListBaseVM<Sys_DicCategory, Sys_DicCategory>
{
    private SqlSugarRepository<Sys_DicCategory> repDicCategory { get; set; }

    /// <summary>
    ///
    /// </summary>
    public DicManagerViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_DicCategory> _repDicCategory, SqlSugarRepository<Sys_DicCategory> _repSearch) : base(dialog, _repDicCategory, _repSearch)
    {
        repDicCategory = _repDicCategory;
        //构造函数
        //Queryable = dc.Client.Queryable<Sys_DicCategory>().OrderBy(o => o.CreateTime);

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #region [     重写     ]

    protected override void InitVM()
    {
    }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ServerViewKeys.EditDicView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    private string ViewKey { get; set; }

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    /// <summary>
    ///     页码改变命令
    /// </summary>
    public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
        new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
            new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    /// <summary>
    ///     页码改变
    /// </summary>
    private void PageUpdated(FunctionEventArgs<int> info)
    {
        EntityList.Clear();

        Page = info.Info;

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    /// <summary>
    /// 新增DicCategory命令
    /// </summary>
    [RelayCommand]
    public void AddNewDicCategory()
    {
        ViewKey = ServerViewKeys.EditDicView;

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(null);
    }

    [RelayCommand]
    public void LookDicCategory(Sys_DicCategory dic)
    {
        //ViewKey = ServerViewKeys.EditDicView;

        //SetDialogWindowSetting(new DialogWindowSetting()
        //{
        //    WindowWidth = 800,
        //    WindowHeight = 600,
        //    IsShowMaxButton = false,
        //    IsShowMinButton = false,
        //    IsOpenWindowSize = false,
        //    TitleFontSize = 15,
        //    CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow)
        //});

        //ExecuteShowDialogWindow(dic);

        BottomContext = WindowsManager.GetInstance().GetView(ServerViewKeys.EditDicView, Param: dic);
    }

    #endregion
}

/// <summary>
/// 编辑字典的VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.EditDicViewModel)]
public partial class EditDicViewModel : BillVM<Sys_DicCategory>
{
    private SqlSugarRepository<Sys_Dic> repDic { get; set; }
    //private SqlSugarRepository<Sys_DicCategory> repDicCategory { get; set; }

    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public EditDicViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_Dic> _repDic, SqlSugarRepository<Sys_DicCategory> _repDicCategory) : base(_repDicCategory)
    {
        repDic = _repDic;
        //repDicCategory=_repDicCategory;
        Dialog = dialog;
    }

    public override void PassData(object obj)
    {
        if (obj == null)
        {
            //新增
            Title = "新增字典类型";
            //Entity.BillId = Guid.NewGuid().ToString();
            HasSave = false;
        }
        else if (obj is Sys_DicCategory dic)
        {
            HasSave = true;
            Title = $"修改 {dic.DicCategoryName} ";
            SetEntity(dic);

            repDic.ToList(w => w.BillId == dic.BillId).ForEach(DicList.Add);
        }
        else
        {
            CloseView(); ;
        }
    }

    public override void InitData()
    {
    }

    public override void BillVmInitData()
    {
    }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    [ObservableProperty]
    public bool isLoading;

    public ObservableCollection<Sys_Dic> DicList { get; set; } = new ObservableCollection<Sys_Dic>();

    [ObservableProperty]
    public bool hasSave;

    [RelayCommand]
    public void Save()
    {
        try
        {
            Rep.BeginTran();

            if (string.IsNullOrEmpty(Entity.BillId))
            {
                var model = Rep.InsertReturnEntity(Entity);

                if (model != null)
                {
                    Entity.BillId = model.BillId;
                    Entity.IsPublic = true;
                    HasSave = true;

                    //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Successful);
                    Dialog.ShowPopupWindow(new PopupWindowSetting()
                    {
                        Message= $"保存成功！",
                        OwnerWindow= WindowsManager.GetInstance().GetDialogWindow(ViewId),
                        Type= MessageType.Successful
                    });
                }
            }
            else
            {
                Rep.Update(Entity);

                var insertlist = DicList.Where(w => string.IsNullOrEmpty(w.DtlId)).ToList();
                var updatellist = DicList.Where(w => !string.IsNullOrEmpty(w.DtlId)).ToList();

                if (insertlist.Count() > 0)
                {
                    repDic.Insert(insertlist);
                }

                if (updatellist.Count() > 0)
                {
                    repDic.Update(updatellist);
                }
            }

            Rep.CommitTran();

            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().MainWindow, MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message="保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type= MessageType.Successful
                });
            else
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = "保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Successful
                });
        }
        catch (Exception ex)
        {
            Rep.CurrentRollbackTran();
            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().MainWindow, MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = MessageType.Error
                });
            else
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Error
                });
        }
    }

    /// <summary>
    /// 添加明细
    /// </summary>
    [RelayCommand]
    public void AddDetail()
    {
        int max = 0;
        if (DicList.Count > 0)
        {
            max = DicList.Max(m => m.DicValue) + 1;
        }

        Sys_Dic vo = new Sys_Dic()
        {
            DicValue = max,
            Description = "描述",
            IsActive = true,
            BillId = Entity.BillId
        };

        DicList.Add(vo);
    }

    /// <summary>
    /// 删除明细
    /// </summary>
    [RelayCommand]
    public void DeleteDetail()
    {
        var deletelist = DicList.Where(w => w.IsChecked).ToList();

        if (deletelist != null && deletelist.Count > 0)
        {
            try
            {
                repDic.CurrentBeginTran();

                repDic.Delete(deletelist.Select(s => s.DtlId).ToArray());

                repDic.CurrentCommitTran();

                deletelist.ForEach(f => DicList.Remove(f));
            }
            catch (Exception ex)
            {
                repDic.CurrentRollbackTran();
                //Dialog.ShowPopupWindow($"删除失败！:{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message= $"删除失败！:{ex.Message}",
                    OwnerWindow= WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type= MessageType.Error
                });
            }
        }
    }
}